<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开放时间" prop="openTimeStart">
        <el-time-picker clearable
          v-model="queryParams.openTimeStart"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
          :picker-options="{selectableRange:'00:00:00-23:59:59'}"
          placeholder="请选择开放时间">
        </el-time-picker>
      </el-form-item>
      <el-form-item label="开放时间结束" prop="openTimeEnd">
        <el-time-picker clearable
          v-model="queryParams.openTimeEnd"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
          :picker-options="{selectableRange:  `${this.queryParams.openTimeStart}-23:59:59`}"
          placeholder="请选择开放时间结束">
        </el-time-picker>
      </el-form-item>
      <el-form-item label="类型" prop="otherBaseType">
        <el-select v-model="queryParams.otherBaseType" placeholder="请选择类型" clearable>
          <el-option
            v-for="dict in dict.type.other_base_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-hasPermi="['ticket:base:query']">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ticket:base:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ticket:base:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ticket:base:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ticket:base:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="baseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="星级" align="center" prop="starDetail" />
      <el-table-column label="营业开始时间" align="center" prop="openTimeStart" width="180">
      </el-table-column>
      <el-table-column label="营业结束时间" align="center" prop="openTimeEnd" width="180">
      </el-table-column>
      <el-table-column label="类型" align="center" prop="otherBaseType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.other_base_type" :value="scope.row.otherBaseType"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="介绍信息" align="center" prop="introduceDetails" /> -->
      <!-- <el-table-column label="游客须知" align="center" prop="touristNotice" /> -->
      <el-table-column label="地理位置" align="center" prop="addressDetails" />
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="130">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ticket:base:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ticket:base:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改（景区、场馆、活动基本信息）对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="dialogIsCloseOnModal" :close-on-press-escape="dialogIsCloseOnModal">
      <el-form ref="form" :model="form" :rules="rules" label-width="106px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="星级" prop="starDetail">
              <el-input-number v-model="form.starDetail" placeholder="请输入星级"  :min="0" :max="10" :precision="1" controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="营业开始时间" prop="openTimeStart">
              <el-time-picker clearable
                v-model="form.openTimeStart"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                :picker-options="{selectableRange:'00:00:00-23:59:59'}"
                placeholder="请选择营业开始时间">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业结束时间" prop="openTimeEnd">
              <el-time-picker clearable
                v-model="form.openTimeEnd"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                :picker-options="{selectableRange:  `${this.form.openTimeStart}-23:59:59`}"
                placeholder="请选择营业结束时间">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item label="介绍信息">
              <editor v-model="form.introduceDetails" :min-height="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item label="游客须知">
              <editor v-model="form.touristNotice" :min-height="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="类型" prop="otherBaseType">
            <el-select v-model="form.otherBaseType" placeholder="请选择类型">
              <el-option
                v-for="dict in dict.type.other_base_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="11" v-if="form.otherBaseType==3">
            <el-form-item label="球场类型" prop="otherBaseVenuesType" :prop="form.otherBaseType==3?'otherBaseVenuesType':'empty'">
              <el-select v-model="form.otherBaseVenuesType" placeholder="请选择类型" >
                <el-option
                  v-for="dict in dict.type.other_base_venues_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" v-if="form.otherBaseType==3">
            <el-form-item label="基础店铺" :prop="form.otherBaseType==3?'sysStoresId':'empty'" >
              <el-select v-model="form.sysStoresId" filterable placeholder="请选择">
                <el-option
                  v-for="item in sysStoresList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>




          <el-col :span="12">
            <el-form-item label="地理位置" prop="addressDetails">
              <el-input v-model="form.addressDetails" placeholder="请输入地理位置" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <span class='islatShows' @click='changeDoit'>{{isLatShowHide?'点我隐藏':'点我选点'}}</span>
          </el-col>
          <el-col :span="24">
              <tx-map @selected="mapSelected" v-if="isLatShowHide" image="" height="500px;" :latitude="form.latitude" :longitude="form.longitude"/>
          </el-col>
          <el-col :span="23">
            <el-form-item label="图片上传" prop="fileList">
              <!-- <image-upload @getFileList='getFileList' ref='imageUploads' :key="timer"/> -->
              <el-upload
                ref="myupload"
                class="upload-demo"
                :limit="limit"
                :action="uploadImgUrl"
                :on-remove="handleRemove"
                :on-success='onSuccess'
                :before-remove="beforeRemove"
                :before-upload="handleBeforeUpload"
                :file-list="fileList"
                :headers="headers"
                :on-exceed="handleExceed"
                accept="image/jpg,image/jpeg,image/png"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过{{fileSize}}MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { listBase, getBase, delBase, addBase, updateBase,listStores } from "@/api/ticket/base";
import ImageUpload from './components/imageUploadAction.vue'
import {getTypeList} from "@/api/ticket/stock";
export default {
  dicts: ['other_base_type','other_base_venues_type'],
  // components:{ImageUpload},
  name: "Base",
  data() {
    return {
      // 图片上传相关
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/uploadAttaData", // 上传的图片服务器地址
      fileList:[],
      // fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
       headers: {
          Authorization: "Bearer " + getToken(),
        },
        value: [String, Object, Array],
        // 图片数量限制
        limit: 5,
        // 大小限制(MB)
        fileSize: 5,
        // 文件类型, 例如['png', 'jpg', 'jpeg']
        fileType:  ["png", "jpg", "jpeg"],
        attaIds:[],
      //基础店铺
      sysStoresList:[],
      timer:'',
      // 遮罩层
      loading: true,
      // 弹框关闭方式
      closeOrmodal:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // （景区、场馆、活动基本信息）表格数据
      baseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isLatShowHide:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        starDetail: null,
        openTimeStart: null,
        openTimeEnd: null,
        introduceDetails: null,
        touristNotice: null,
        addressDetails: null,
        longitude: null,
        latitude: null,
        isDel: null,
        name: null
      },
      // 查询参数
      queryParamsStock: {
        bizType: null,
        uscc: null,
        name: null,
        status: null,
        picName: null,
        picPhone: null,
        isDel: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sysStoresId: [
          { required: true, message: "基本店铺选择不能为空", trigger: "blur" }
        ],
        otherBaseVenuesType: [
          { required: true, message: "球场类型不能为空", trigger: "blur" }
        ],
        name:[
          { required: true, message: "请输入名称", trigger: "blur" }
        ],
        // openTimeStart:[
        //   { required: true, message: "请选择营业开始时间", trigger: "change" }
        // ],
        // openTimeEnd:[
        //   { required: true, message: "请选择营业结束时间", trigger: "change" }
        // ],
        otherBaseType:[
          { required: true, message: "请选择类型", trigger: "change" }
        ],
        addressDetails:[
          { required: true, message: "请输入地理位置", trigger: "blur" }
        ],
        fileList:[
          { required: true, validator: this.checkUserName, trigger: 'change' },
        ]

      },
    };
  },
  created() {
    this.getList();
  },
  mounted(){
  },
  methods: {
    changeDoit(){
      this.isLatShowHide=!this.isLatShowHide
    },
    mapSelected(point) {
      this.form.latitude = point.lat;
      this.form.longitude = point.lng;
    },
    checkUserName(rule, value, callback){
        value = this.fileList;
        if (value.length<=0)
          callback(new Error("请上传图片"));
        else
          callback();
      },
    // 获取票种下拉列表
    getsysStoresList(){

      listStores(this.queryParamsStock).then(response => {
        this.sysStoresList = response.data;
      });
    },


    // 图片上传
    handleBeforeUpload(file) {
      console.log(file)
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
      handleRemove(file, fileList) {
        this.fileList=fileList
        console.log(file, fileList,this.attaIds);
        this.toParent()
      },
      beforeRemove(file, fileList){
        fileList.map((item,index)=>{
          if(item.uid==file.uid){
            this.attaIds.splice(index,1)
          }
        })
      },
      onSuccess(res,file,fileList){
        this.fileList=fileList
        this.attaIds.push(res.data.attaId)
        this.toParent()
      },
      toParent(){
        this.form.attaIds=this.attaIds.join(',')
        // this.$emit('getFileList',this.attaIds)
      },
      clearImage(){
        console.log('clearImage',this.$refs.myupload)
        this.$refs.myupload.clearFiles()
      },
    // 获取图片上传列表
    getFileList(attaIds){
      this.form.attaIds=attaIds.join(',')
    },
    /** 查询（景区、场馆、活动基本信息）列表 */
    getList() {
      this.loading = true;
      listBase(this.queryParams).then(response => {
        this.baseList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(err=>{
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ticOtherId: null,
        starDetail: null,
        openTimeStart: null,
        openTimeEnd: null,
        introduceDetails: null,
        touristNotice: null,
        addressDetails: null,
        longitude: null,
        latitude: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDel: null,
        name: null,
        attaIds:[]
      };
      
      this.attaIds=[]
      this.resetForm("form");
      // 重置图片上传组件fileList
      this.timer=new Date().getTime()
      this.isLatShowHide = false
      console.log('isLatShowHide',this.isLatShowHide)
      // 清空图片上传
      this.$nextTick(()=>{
        if(this.$refs.myupload){
          this.$refs.myupload.clearFiles()
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ticOtherId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加（景区、场馆、活动基本信息）";
      this.getsysStoresList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getsysStoresList();
      const ticOtherId = row.ticOtherId || this.ids
      getBase(ticOtherId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改（景区、场馆、活动基本信息）";
        let temp=[]
        response.data.commAttachmentList.map(item=>{
            temp.push({name:item.attaName,url:`${item.attaPath}`})
            this.attaIds.push(item.attaId)
        })
        this.fileList=temp
        console.log(this.fileList)
      });
    },
    /** 提交按钮 */
    submitForm() {
      // const formData = new FormData();
      // let obj = { ...this.form };
      // Object.keys(obj).forEach(key => {
      //   formData.append(key, obj[key]);
      // });
      // for (let i = 0; i < this.fileList.length; i++) {
      //   formData.append("files",this.fileList[i].raw);
      //   console.log(formData)
      // }
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ticOtherId != null) {
            updateBase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.$nextTick(()=>{
                this.clearImage()
              })
            });
          } else {
            addBase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.$nextTick(()=>{
                this.clearImage()
              })
            });
          }
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ticOtherIds = row.ticOtherId || this.ids;
      this.$modal.confirm('是否确认删除（景区、场馆、活动基本信息）编号为"' + ticOtherIds + '"的数据项？').then(function() {
        return delBase(ticOtherIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ticket/base/export', {
        ...this.queryParams
      }, `base_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-date-editor.el-input{
  width:100%;
}
.islatShows{
    font-size: 12px;
    border-bottom: 1px solid;
    cursor: pointer;
    margin: 8px 0 0 10px;
    display: inline-block;
}
</style>
